﻿using AlarmPlatformInterface.Comm;
using AlarmPlatformInterface.DMs;
using Entity.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Utility;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace AlarmPlatformInterface.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        // GET: api/<LoginController>
        [HttpGet]
        public ContentResult Get(ReqBaseModel req)
        {
            string conn = Global.Configuration["ConnectionStrings:DDb"];
            using (Entity.DBContext context = Entity.BaseContext.CreateContext(conn))
            {

            }

            return Login(req);
        }

        // POST api/<LoginController>
        [HttpPost]
        public ContentResult Post([FromBody] ReqBaseModel req)
        {
            return Login(req);
        }

        private ContentResult Login(ReqBaseModel data)
        {
            ResBaseModel r = new ResBaseModel();
            try
            {
                string sign = Utility.Security.Sign(data.Parameters, data.Token);
                if (sign != data.Sign)
                {
                    WriteLog.WriteExceptionFile($"页面传输数据异常：{data.SerializerObjectToString()}");
                    return Content(JsonConvert.SerializeObject(r));
                }
                string parameters = data.Parameters.Decrypt("ht123456");
                string pLower = parameters.ToLower();
                if (pLower.Contains("select") || pLower.Contains("insert")
                   || pLower.Contains("update") || pLower.Contains("delete")
                   || pLower.Contains("drop") || pLower.Contains("from"))
                {
                    WriteLog.WriteExceptionFile($"页面传输数据异常：{data.SerializerObjectToString()}");
                    return Content(JsonConvert.SerializeObject(r));
                }
                ReqLoginModel reqLogin = parameters.JSONStringToObject<ReqLoginModel>();
                using (Entity.DBContext context = Entity.BaseContext.CreateContext(Global.Configuration["ConnectionStrings:DDb"]))
                {
                    OperatorInfo uinfo = context.operatorInfos.Where(p => p.LoginName == reqLogin.UserName && p.Password == reqLogin.Pwd && p.LimitLogin != 1).FirstOrDefault();
                    if (uinfo != null)
                    {
                        RoleInfo role = context.roleInfos.Where(p => p.RoleId == uinfo.RoleId).FirstOrDefault();
                        ResLoginModel resLogin = new ResLoginModel();
                        if (role.SuperAdmin.HasValue && role.SuperAdmin == 1)
                        {
                            resLogin.IsGroupCompany = true;
                        }
                        else
                        {
                            resLogin.RoleRights = role.RoleRights;
                            List<string> arrrights = role.RoleRights.Split(',').ToList();
                            if (arrrights.Where(p => p.StartsWith('C')).Count() > 1)
                            {
                                resLogin.IsGroupCompany = true;
                            }
                        }

                        r.IsSuccess = true;
                        r.Token = Extensions.DesEncrypt(uinfo.LoginName + "|" + uinfo.Password + "|" + DateTime.Now.ToString("yyyyMMddHHmmssff"), Global.Configuration["AppSettings:CryptKey"]);
                        resLogin.Token = r.Token;
                        r.Result = resLogin.SerializerObjectToString();
                    }
                    else
                    {
                        r.FailType = eFailType.LoginFail.ToString();
                        r.Result = "登录名或者密码错误！登录失败！";
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteExceptionFile("Login Controller : " + ex.Message + "\r\n" + ex.StackTrace);
                r.FailType = eFailType.ServerError.ToString();
                r.Result = "服务器错误！";
            }
            string s = JsonConvert.SerializeObject(r);
            return Content(s);
        }
    }

    public class ReqLoginModel
    {
        public string UserName { get; set; }
        public string Pwd { get; set; }
    }
    public class ResLoginModel
    {
        public string Token { get; set; }
        public string RoleRights { get; set; }
        public bool IsGroupCompany { get; set; }
    }
}
